package com.hgl.bi.common.manager;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @program: BI
 * @description: Redis管理类
 * @author: hgl
 * @create: 2025-02-12 21:22
 */
@Component
public class RedisManager {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public void setObj(String key, Object value, long expire) {
        try {
            String jsonValue = objectMapper.writeValueAsString(value);
            // 将 JSON 字符串存储到 Redis
            redisTemplate.opsForValue().set(key, jsonValue, expire, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new RuntimeException("Failed to serialize object", e);
        }
    }

    public Object get(String key, Class<?> clazz) {
        try {
            String jsonValue = (String) redisTemplate.opsForValue().get(key);
            if (jsonValue == null) {
                return null;
            }
            // 将 JSON 字符串反序列化为指定类型的对象
            return objectMapper.readValue(jsonValue, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to deserialize object", e);
        }
    }

    // ---------------------- 通用操作 ----------------------

    /**
     * 设置过期时间
     *
     * @param key     键
     * @param timeout 时间（秒）
     */
    public Boolean expire(String key, long timeout) {
        if (timeout > 0) {
            return redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
        }
        return false;
    }

    /**
     * 删除键
     */
    public Boolean delete(String key) {
        Boolean deleted = redisTemplate.delete(key);
        return deleted;
    }

    // ---------------------- String操作 ----------------------

    /**
     * 存储键值（带过期时间）
     */
    public void set(String key, Object value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 获取值
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // ---------------------- 哈希表操作 ----------------------

    public void hPut(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    // ---------------------- 其他常用操作（按需添加）--------------------

    // 列表操作
    public void lPush(String key, Object value) {
        redisTemplate.opsForList().leftPush(key, value);
    }

    // 集合操作
    public void sAdd(String key, Object... values) {
        redisTemplate.opsForSet().add(key, values);
    }

    // ---------------------- 分布式锁 ----------------------

    /**
     * 尝试获取分布式锁（简单实现）
     *
     * @param key     锁的key
     * @param value   请求标识（可用UUID）
     * @param timeout 超时时间（秒）
     */
    public Boolean tryLock(String key, String value, long timeout) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(result);
    }

    /**
     * 释放锁
     */
    public void unlock(String key) {
        redisTemplate.delete(key);
    }
}
